package cn.acewill.yxd.yunxundian.ui.user;

import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListView;
import android.widget.RelativeLayout;

import com.afollestad.materialdialogs.DialogAction;
import com.afollestad.materialdialogs.MaterialDialog;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import org.xutils.DbManager;
import org.xutils.common.Callback;
import org.xutils.ex.DbException;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.io.File;
import java.io.IOException;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import cn.acewill.yxd.yunxundian.BaseActivity;
import cn.acewill.yxd.yunxundian.R;
import cn.acewill.yxd.yunxundian.YXDAPP;
import cn.acewill.yxd.yunxundian.adapter.ToolListAdapter;
import cn.acewill.yxd.yunxundian.componet.NetWorkStateReceiver;
import cn.acewill.yxd.yunxundian.model.aCloudBean;
import cn.acewill.yxd.yunxundian.pubClass.OkHttpManger;
import cn.acewill.yxd.yunxundian.pubClass.pubClass;
import cn.acewill.yxd.yunxundian.ui.MainActivity;
import cn.acewill.yxd.yunxundian.utils.MaterialDialogUtils;
import cn.acewill.yxd.yunxundian.utils.OpenFileUtils;


/**
 * Created by XXX on 2017/4/3.
 */
public class ToolBoxInfoActivity extends BaseActivity implements AdapterView.OnItemClickListener{
    protected YXDAPP yxdapp=new YXDAPP();
    protected DbManager db = x.getDb(yxdapp.getDaoConfig());
    private ListView toolList;
    private ToolListAdapter adapter;
    //文件存储的路径
   // private String path=Environment.getExternalStorageDirectory().getPath() + File.separator+"/cn.acewill.yxd/downloads/";
    private ProgressDialog progressDialog;
    private RelativeLayout loadingview;
    private List<aCloudBean> myfileList;
    private aCloudBean cloudBean;
    private static int openid=0;
    private boolean isresume =false;
    //点击的文件路径
    private  String thispath;
    //视频播放路径
    private String playpath=pubClass.SecondIP+"/PAD/tools/toolF/";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        setTitleBar("工具箱");
        setContentView(R.layout.tool_box_toollist);
        super.onCreate(savedInstanceState);
        initView();
        if(NetWorkStateReceiver.whetherConnectNetWork==1)
        {
            setShowOrGone(1);
            LoadFolder();
        }else{
//            //加载本地的文件
//            File file =new File(path);
//            if (!file.exists()){
//                showAnimaDialog("本地文件不存在，请在网络条件下加载");
 //           }
                //存在则进行本地读取,先预读id=0的数据
                try {
                    List<aCloudBean> aCloud=db.selector(aCloudBean.class).where("parentId","=",0).findAll();
                    setShowOrGone(2);
                    if (aCloud!=null&&aCloud.size()>0){
                        adapter=new ToolListAdapter(this,aCloud);
                        toolList.setAdapter(adapter);
                    }else{
                        showAnimaDialog(ToolBoxInfoActivity.this,"无本地存储文件，请在网路下加载数据");
                    }
                } catch (DbException e) {
                    e.printStackTrace();
                }
            }
    }
    @Override
    protected void onResume() {
        super.onResume();
        if (isresume){
            try {
                myfileList = db.selector(aCloudBean.class).where("parentid","=",openid).findAll();
                adapter =new ToolListAdapter(this,myfileList);
                toolList.setAdapter(adapter);
                adapter.notifyDataSetChanged();
            } catch (DbException e) {
                e.printStackTrace();
            }
        }
        isresume=true;
    }

    public void initView(){
        Button sureBtn = (Button) findViewById(R.id.sureBtn);
        sureBtn.setVisibility(View.GONE);
        this.toolList= (ListView) findViewById(R.id.toolList);
        this.toolList.setOnItemClickListener(this);
        this.loadingview= (RelativeLayout) findViewById(R.id.loadingRel);
    }

    /*加载文件夹*/
    public void LoadFolder(){
        Map<String,String> map=new HashMap<>();
        map.put("empid", MainActivity.id+"");
        map.put("task","loadToolF");
        try {
            OkHttpManger.getInstance().postAsync(pubClass.Server_namehzm, new OkHttpManger.MyCallback() {
                @Override
                public void onSuccess(String result) {
                    /**
                     *1.第一次请求将文件夹数据存储到本地
                     */
                    setShowOrGone(2);
                    String[] arry=result.split("\\|");
                    if (arry[0].equals("200")){
                        //存储到本地数据库
                        Gson gson=new Gson();
                        Type typelist=new TypeToken<ArrayList<aCloudBean>>(){
                        }.getType();
                        ArrayList<aCloudBean> aCloudBeanArrayList= gson.fromJson(pubClass.convertToArrayJson(result), typelist);
                        aCloudBean ac= null;
                        //删除已存在的数据
                        try {
                            ac = db.selector(aCloudBean.class).findFirst();
                            if (ac!=null){
                                db.dropTable(aCloudBean.class);
                            }
                            if (aCloudBeanArrayList!=null&&aCloudBeanArrayList.size()>0)
                                 db.saveOrUpdate(aCloudBeanArrayList);
                            else{
                                BaseActivity.showAnimaDialog(ToolBoxInfoActivity.this,"现在还有有任何工具哦");
                                return;
                            }

                        } catch (DbException e) {
                            e.printStackTrace();
                        }
//                        for (aCloudBean aa:aCloudBeanArrayList){
//                            try {
//                                db.saveOrUpdate(aa);
//                            } catch (DbException e) {
//                                e.printStackTrace();
//                            }
//                        }
                        //进行本地数据的查询
                        try {
                            cloudBean=db.selector(aCloudBean.class).where("parentId","=",0).findFirst();
                            if (cloudBean!=null){
                                //获取下一层的数据
                                myfileList = db.selector(aCloudBean.class).where("parentId","=",cloudBean.getId()).findAll();
                                if (myfileList!=null&&myfileList.size()>0){
                                    adapter=new ToolListAdapter(ToolBoxInfoActivity.this,myfileList);
                                    toolList.setAdapter(adapter);
                                }else{
                                    showToast(ToolBoxInfoActivity.this,"无文件数据");
                                }
                            }
                        } catch (DbException e) {
                            e.printStackTrace();
                        }
                    }
                    if (arry[0].equals("201")){
                        showAnimaDialog(ToolBoxInfoActivity.this,arry[1]);
                    }
                }
                @Override
                public void onFailture() {
                    //捕获请求超时
                    setShowOrGone(3);
                    showAnimaDialog(ToolBoxInfoActivity.this,"数据请求失败");
                }
            },map);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
       final aCloudBean bean= (aCloudBean) parent.getItemAtPosition(position);
        try {
            myfileList= db.selector(aCloudBean.class).where("parentId","=",bean.getId()).findAll();
            if (myfileList==null||myfileList.size()==0){
                if (bean.getType().equals("menuTreeRoot")||bean.getType().equals("folder")){
                    showAnimaDialog(ToolBoxInfoActivity.this,"当前目录没有更多文件");
                }else{
                    //parentId的数据下载

                    if (bean.getExt().equals("mp4")||bean.getExt().equals("mov")){
                         thispath =pubClass.videoDownLoadPath+bean.getName()+"."+bean.getExt();
                    }else{
                         thispath =pubClass.wordPdfUri+bean.getName()+"."+bean.getExt();
                    }
                    thispath=thispath.replace("//","/");
                    File file =new File(thispath);
                    openid=bean.getParentId();
                    if(file.exists()){
                        //判断是否是视频文件
                        if (bean.getExt().equals("mp4")||bean.getExt().equals("mov")){
                            //startActivity(OpenFileUtils.openFile(dpath));
                             startActivity(new Intent(ToolBoxInfoActivity.this,ToolVideoPlayActivity.class).putExtra("path",thispath).putExtra("name",bean.getName()));
                        }else{
                            try {
                                startActivity(OpenFileUtils.openFile(thispath));
                            }catch (Exception e){
                                BaseActivity.showAnimaDialog(ToolBoxInfoActivity.this,"未检测到可打开的软件");
                            }
                        }
                    }else{
                        if (NetWorkStateReceiver.whetherConnectNetWork==1){
                            if (NetWorkStateReceiver.netWorkType!=1){
                                String mysize = ToolListAdapter.getDataSize(bean.getSize());
                                MaterialDialogUtils.showMaterialDialog(this, "当前使用是移动网络，将产生"+mysize+"流量，是否继续", "确定", "取消", true, false,
                                        new MaterialDialog.SingleButtonCallback() {
                                            @Override
                                            public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                                                if (bean.getExt().equals("mp4")||bean.getExt().equals("mov")){
                                                    startActivity(new Intent(ToolBoxInfoActivity.this,ToolVideoPlayActivity.class).putExtra("path",playpath+bean.getPath()).putExtra("name",bean.getName()));
                                                    //开启下载
                                                    downloadFile(pubClass.Server_namehzm+"?task=downloadF&fid="+bean.getId(),thispath,0,bean.getId());
                                                }else{
                                                    //下载文件
                                                    downloadFile(pubClass.Server_namehzm+"?task=downloadF&fid="+bean.getId(),thispath,1,bean.getId());
                                                }
                                            }
                                        }, new MaterialDialog.SingleButtonCallback() {
                                            @Override
                                            public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                                            }
                                        });
                            } else{
                                if (bean.getExt().equals("mp4")||bean.getExt().equals("mov")){
                                    startActivity(new Intent(ToolBoxInfoActivity.this,ToolVideoPlayActivity.class).putExtra("path",playpath+bean.getPath()).putExtra("name",bean.getName()));
                                    //开启下载
                                    downloadFile(pubClass.Server_namehzm+"?task=downloadF&fid="+bean.getId(),thispath,0,bean.getId());
                                }else{
                                    //下载文件
                                    downloadFile(pubClass.Server_namehzm+"?task=downloadF&fid="+bean.getId(),thispath,1,bean.getId());
                                }
                            }
                        }else showAnimaDialog(this,"当前无网络连接");
                    }
                }
            }else{
                adapter=new ToolListAdapter(this,myfileList);
                toolList.setAdapter(adapter);
                adapter.notifyDataSetChanged();
            }
        } catch (DbException e) {
            e.printStackTrace();
        }
    }

    private Callback.Cancelable cancelable;
    private int fileid = 0; //如果没有下载完
    private void downloadFile(final String url, String path, final int code,int id) {
        progressDialog = new ProgressDialog(this);
        progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        progressDialog.setMessage("努力下载中....");
        progressDialog.show();
        progressDialog.setCanceledOnTouchOutside(true);
        progressDialog.setOnKeyListener(new DialogInterface.OnKeyListener() {
            @Override
            public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
                if (keyCode == KeyEvent.KEYCODE_BACK){
                    return true;
                }
                return false;
            }
        });
        RequestParams requestParams = new RequestParams(url);
        requestParams.setSaveFilePath(path);
        requestParams.setAutoResume(true);
        requestParams.isCancelFast();

            if (fileid==id){ //继续下载。不重新开启
                return;
            }
            fileid=id;
            cancelable=x.http().get(requestParams, new Callback.ProgressCallback<File>() {
                @Override
                public void onWaiting() {
                }
                @Override
                public void onStarted() {
                }
                @Override
                public void onLoading(long total, long current, boolean isDownloading) {

                    if (code==0){ //下载视频
                        float percent=(float) Math.round(current)/1024/1024;
                        Log.e("progress",percent+"");
                    }else{

                        progressDialog.setProgress((int)current);
                        progressDialog.setMax((int) total);
                        float all=(float) Math.round(total)/1024/1024;
                        float percent=(float) Math.round(current)/1024/1024;
                        progressDialog.setProgressNumberFormat(String.format("%.3fM/%.3fM",percent,all));
                    }
                }
                @Override
                public void onSuccess(File result) {
                    progressDialog.dismiss();
                    //打开文件
                    if (code!=0){
                        startActivity(OpenFileUtils.openFile(result.getPath()));
                    }
                }
                @Override
                public void onError(Throwable ex, boolean isOnCallback) {
                    ex.printStackTrace();
                    showAnimaDialog(ToolBoxInfoActivity.this,"下载失败");
                    progressDialog.dismiss();
                }
                @Override
                public void onCancelled(CancelledException cex) {
                }
                @Override
                public void onFinished() {
                }
            });
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {

        if (keyCode==KeyEvent.KEYCODE_BACK) {
            goback();
        }
       return true;
    }

    public void goback(){
        //拿到当前数据的parentid;
        if (myfileList==null||myfileList.size()==0){
            finish();
        }else{
            int fileid=myfileList.get(0).getParentId();
                try {
                    //上层文件的parentid = 0
                    aCloudBean aCloudBean= db.selector(aCloudBean.class).where("Id","=",fileid).findFirst();
                    int parentid=aCloudBean.getParentId();
                    if (parentid==0){
                        finish();
                        if (cancelable!=null){
                            cancelable.cancel();
                        }
                        return;
                    }
                    List<aCloudBean> parentList = db.selector(aCloudBean.class).where("parentId", "=", parentid).findAll();
                    if (parentList != null && parentList.size() > 0) {
                        myfileList = new ArrayList<>();
                        myfileList.addAll(parentList);
                    }
                    adapter=new ToolListAdapter(this,myfileList);
                    toolList.setAdapter(adapter);
                    adapter.notifyDataSetChanged();
                } catch (DbException e) {
                    e.printStackTrace();
                }
            }
    }

    public void setShowOrGone(int k){
        if (k==1){
            loadingview.setVisibility(View.VISIBLE);
            toolList.setVisibility(View.GONE);
        }
        if (k==2){
            loadingview.setVisibility(View.GONE);
            toolList.setVisibility(View.VISIBLE);
        }
        if (k==3){
            loadingview.setVisibility(View.GONE);
        }
    }

}
